package com.richdataco;

import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.PluginResult;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaWebView;
import org.json.JSONArray;
import org.json.JSONException;

import android.content.Context;
import android.app.Application;
import android.widget.Toast;
import com.alibaba.security.rp.RPSDK;

/**
 * This class echoes a string called from JavaScript.
 */
public class OcrRichdataco extends CordovaPlugin {
    private Context appContext;
    public static final String ERROR_INVALID_PARAMETERS = "参数格式错误";
    /**
     * JS回调接口对象
     */
    public static CallbackContext cb = null;
    @Override
    public void initialize(CordovaInterface cordova, CordovaWebView webView) {
        super.initialize(cordova, webView);
        appContext = cordova.getActivity().getApplicationContext();
        // 初始化实人认证 SDK
        RPSDK.initialize(appContext);
    }
    @Override
    public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
        if (action.equals("ocrScan")) {
            cb = callbackContext;
            String verifyToken = args.getString(0);
            PluginResult pluginResult = new PluginResult(PluginResult.Status.NO_RESULT);
            pluginResult.setKeepCallback(true);
            cb.sendPluginResult(pluginResult);
            this.ocrScan(verifyToken, callbackContext);
            return true;
        }
        return false;
    }

    private boolean  ocrScan(String verifyToken, final CallbackContext callbackContext) {
            RPSDK.start(verifyToken,cordova.getActivity().getApplicationContext(), new RPSDK.RPCompletedListener() {
                @Override
                public void onAuditResult(RPSDK.AUDIT audit, String code) {
                    Toast.makeText(cordova.getActivity().getApplicationContext(), audit + "", Toast.LENGTH_SHORT).show();
                    if (audit == RPSDK.AUDIT.AUDIT_PASS) {
                        // 认证通过。建议接入方调用实人认证服务端接口DescribeVerifyResult来获取最终的认证状态，并以此为准进行业务上的判断和处理
                        callbackContext.success();
                        // do something
                    } else if(audit == RPSDK.AUDIT.AUDIT_FAIL) {
                        // 认证不通过。建议接入方调用实人认证服务端接口DescribeVerifyResult来获取最终的认证状态，并以此为准进行业务上的判断和处理
                        callbackContext.error("AUDIT_FAIL");
                        // do something
                    } else if(audit == RPSDK.AUDIT.AUDIT_NOT) {
                        // 未认证，具体原因可通过code来区分（code取值参见下方表格），通常是用户主动退出或者姓名身份证号实名校验不匹配等原因，导致未完成认证流程
                        // do something
                        callbackContext.error("AUDIT_NOT");
                    }
                }
            });
        return  true;
    }
}
